<template>
  <div>
    <!-- 添加返回按钮 -->
    <el-button @click="goBack" style="margin-bottom: 20px;">返回</el-button>
    <h1>Param Config Page</h1>
    <p>Title: {{ template }}</p>
    <div v-for="(part, index) in value2Parts" :key="index">
      <p>{{ '{'+ index + "}" + " " + part  }}</p>
      <el-input v-model="inputs[index]" type="textarea" placeholder="要替换的词放这, 英文逗号分割" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router' // 添加 useRouter 导入

const route = useRoute()
const router = useRouter() // 初始化路由

// 添加 goBack 方法
const goBack = () => {
  router.go(-1)
}

const template = ref('')
const value0 = ref('')
const value2 = ref('')
const inputs = ref([])

onMounted(() => {
  value0.value = route.query.value0 as string
  value2.value = route.query.value2 as string
  template.value = cacTemplate(value0.value, value2.value)
  console.log('Value0:', value0.value)
  console.log('Value2:', value2.value)
  console.log('template:', template.value)
  // 从 localStorage 中恢复 inputs 数组
  const savedInputs = localStorage.getItem('inputs');
  if (savedInputs) {
    inputs.value = JSON.parse(savedInputs);
  }
})

const value2Parts = computed(() => {
  return value2.value.split(',')
})

const cacTemplate = (str, keyWord) => {
  const strArr = keyWord.split(',')
      .map(item => item.trim())
      .map(item => [item + ',', ' ' + item + ' ', item + ' '])
  console.log(strArr)
  strArr.forEach((item, index) => {
    item.forEach(i => {
      str = str.replaceAll(i, ' {' + index + '} ')
    })
  })
  return str
}

// 添加 handleCommandEnter 函数
const handleCommandEnter = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { // Command + Enter for Mac, Ctrl + Enter for Windows
    event.preventDefault()
    validateAndNavigate()
  }
}

// 添加 validateAndNavigate 函数
const validateAndNavigate = () => {
  console.log('inputs:', inputs.value) // 打印 inputs 数组
  router.push({ path: '/picGen', query: { value0: value0.value, value2: value2.value, inputs: inputs.value, template: template.value} }); // 跳转到 picGen 页面
}

// 添加键盘事件监听
onMounted(() => {
  window.addEventListener('keydown', handleCommandEnter)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleCommandEnter)
  // 保存 inputs 数组到 localStorage
  localStorage.setItem('inputs', JSON.stringify(inputs.value));
})

</script>

<style scoped>

</style>